from flask import request, abort, current_app, make_response, Response

from info.libs.captcha.pic_captcha import captcha
from info.modules import passport
from info.modules.passport import passport_blu
from info.utils.constants import IMAGE_CODE_REDIS_EXPIRES

# 获取图片验证码
@passport_blu.route('/get_img_code')
def get_img_code():
    # 获取参数
    img_code_id = request.args.get("img_code_id")
    # 校验参数
    if not img_code_id:
        return abort(403)

    # 生成图片验证码
    img_name, img_text, img_bytes = captcha.generate_captcha()

    # 保存验证码文字和图片key  选择redis  快/过期时间/满足键值结构
    try:
        from info import rs
        rs.set("img_code_id_" + img_code_id, img_text, ex= IMAGE_CODE_REDIS_EXPIRES)
    except BaseException as e:
        current_app.logger.error(e)  # 错误信息记录到日志中
        return abort(500)

    # 返回验证码图片  设置content-type,需要自定义响应对象
    response = make_response(img_bytes)  # type: Response
    response.content_type = "image/jpeg"
    return response